import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken (state, token) {
    state.token = token
    setToken(token)
  },
  removeToken (state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login (context, data) {
    const token = await login(data)

    context.commit('setToken', token)

    setTimeStamp()
  },
  async getUserInfo (context) {
    const info = await getUserInfo()
    const result = await getUserDetailById(info.userId)

    const userInfo = {...info, ...result }

    context.commit('setUserInfo', userInfo)
    return userInfo   // 返回用户资料
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    // 1. 退出的时候，要重置路由实例
    resetRouter()
    // 2. 清除 permissions 模块里面state里面的routes
    // 需求：如何在A模块的action里面 调用 B模块的 mutations或者action
    // context.commit('setRoutes',[]) 
    // 错误的！ 这样写是调用当前模块的setRoutes
    // context.commit('permission/setRoutes',[])
    // 错误的！ 这样写是调用当前模块的的子模块permission模块里的mutations里的setRoutes
    context.commit('permission/setRoutes',[],{ root:true })
    // 传入第三个参数，配置项，表示从根模块开始去查找调用
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

